package com.cxz.wanandroid.ui.activity

import android.view.View
import com.cxz.wanandroid.R
import com.cxz.wanandroid.base.BaseMvpActivity
import com.cxz.wanandroid.constant.Constant
import com.cxz.wanandroid.event.LoginEvent
import com.cxz.wanandroid.ext.showToast
import com.cxz.wanandroid.mvp.contract.LoginContract
import com.cxz.wanandroid.mvp.model.bean.LoginData
import com.cxz.wanandroid.mvp.presenter.LoginPresenter
import com.cxz.wanandroid.utils.Preference
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.toolbar.*
import org.greenrobot.eventbus.EventBus

class LoginActivity : BaseMvpActivity<LoginContract.View, LoginContract.Presenter>(),
    LoginContract.View {
    /**
     * local username
     */
    private var user: String by Preference(Constant.USERNAME_KEY, "")
    private var pwd: String by Preference(Constant.PASSWORD_KEY, "")
    private var token: String by Preference(Constant.TOKEN_KEY, "")

    override fun attachLayoutRes(): Int = R.layout.activity_login
    override fun useEventBus(): Boolean = false
    override fun enableNetworkTip(): Boolean = false

    override fun initView() {
        super.initView()
        et_username.setText(user)
        toolbar.run {
            title = resources.getString(R.string.login)
            setSupportActionBar(this)
            //给左上角图标的左边加上一个返回的图标 。对应ActionBar.DISPLAY_HOME_AS_UP
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        btn_login.setOnClickListener(onClickListener)
        tv_sign_up.setOnClickListener(onClickListener)
    }

    override fun initData() {

    }

    override fun start() {

    }

    override fun createPresenter(): LoginContract.Presenter = LoginPresenter()

    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.btn_login -> {
                login()
            }
            R.id.tv_sign_up -> {
                showToast("tv_sign_up")
            }
        }
    }

    private fun login() {
        if (validate()) {
            mPresenter?.loginWanAndroid(et_username.text.toString(), et_password.text.toString())
        }
    }

    private fun validate(): Boolean {
        var valid = true
        val username = et_username.text.toString()
        val password = et_password.text.toString()
        if (username.isEmpty()) {
            et_username.error = "用户名不能为空"
            valid = false
        }
        if (password.isEmpty()) {
            et_password.error = "密码不能为空"
            valid = false
        }
        return valid
    }

    override fun loginSuccess(data: LoginData) {
        showToast(getString(R.string.login_success))
        isLogin = true
        user = data.username
        pwd = data.password
        token = data.token
        EventBus.getDefault().post(LoginEvent(true))
        finish()
    }
}